import axios from 'axios'
import Env from './env'
import Router from './router'
import moment from 'moment'
import Qs from 'qs'

let $http = axios.create({
  baseURL: Env.apiBaseUrl,
  timeout: 30000,
  globalErrorHandle: true,
  paramsSerializer: function (params) {
    return Qs.stringify(params, {
      serializeDate: (date) => {
        return moment(date).format('YYYY-MM-DD HH:mm:ss')
      },
      indices: false
    })
  },
  transformRequest: [function (data, headers) {
    return JSON.stringify(data, (key, value) => {
      // Filtering out properties
      let realValue = data && data[key]
      if (realValue && realValue instanceof Date) {
        return moment(realValue).format('YYYY-MM-DD HH:mm:ss')
      }
      return value
    })
  }]
})

// don't know why transformRequest setting will break default content-type settings
$http.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'

// 为请求添加 x-auth-token 头
$http.interceptors.request.use(function (config) {
  // update auth token if token exists
  const profile = localStorage.getObject('profile')
  if (profile && profile.token) {
    config.headers['X-auth-token'] = profile.token
    config.headers['X-identify'] = encodeURI(profile.dtbShortName)
    // config.globalErrorHandle = true
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

// 添加响应拦截器, 处理请求异常
$http.interceptors.response.use(function (response) {
  const resp = response.data
  if (resp && resp.result) {
    return resp.data
  } else {
    if (response.config.globalErrorHandle) {
      const message = `[${resp.code}] ${resp.message}`
      Router.app.$confirm(message, '操作失败', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'error'
      })
    }
    return Promise.reject(response)
  }
}, function (error) {
  // 服务器响应的状态码>=400
  const resp = error.response
  if (resp) {
    if (resp.status === 401) {
      const errorCode = resp.data.code
      if (errorCode === 4010) { // login required
        // remove invaild token if exists
        let profile = localStorage.getObject('profile')
        profile && (delete profile.token)
        localStorage.setObject('profile', profile)
        // better way to get router&route?
        const current = Router.app._route.fullPath
        Router.app._router.push({ name: 'login', query: { success: current } })
      } else if (errorCode === 4011) { // not permit
        Router.app.$confirm('您没有该操作的权限', '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning'
        })
      }
    }

    // migration
    if (resp.status === 503 && resp.data.code === 5030) {
      Router.app.$alert('系统升级中，预计需要2分钟', '系统升级')
    } else if (resp.status >= 500) {
      Router.app.$confirm('服务器出错，无法执行您的操作，请联系管理员', '操作失败', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'error'
      })
    }
  } else {
    console.log('Error', error.message)
  }

  return Promise.reject(error)
})

// short cut for get with params
$http.$get = function (url, params) {
  return $http.get(url, {
    params: params
  })
}

export default $http
